<template>
	<view>
		<uni-nav-bar @clickLeft="back" fixed="true" color="#333" left-icon="left" backgroundColor="#fff" :title="title"
			statusBar="true" :border="false" />
		<view class="py-24 px-20">
			<view class="" v-if="skuAmend == 2">
				<view class="bg-FFF round-12 py-20 px-20 flex items-center justify-between">
					<view class="text-28 font-700">
						商品规格
					</view>
					<view class="color-fff bg-F41717 border-r24 box-1" style="line-height: 48rpx;padding: 0 24rpx;"
						@click="selectSpecification">
						选择
					</view>
				</view>
				<view class="fontS-20 mt-20">
					提示:<text style="color: #F42F2B;">1.所有内容除原价非必填2.商品规格和规格值的修改会重置规则值对应的数据设置</text>
				</view>
			</view>

			<view class="box-3 round-12 py-24 px-20 mt-32" v-if="commercialSpecification.length != 0"
				v-for="(item,index) in commercialSpecification" :key="index">
				<view class="text-32 font-700 text-center py-20">
					商品规格
				</view>
				<view class="">
					<view class="flex items-center justify-between py-20">
						<view class="text-28 ">
							属性值：
						</view>
						<view class="text-28 flex items-center" @click="deleteSpecification(index)">
							<view class="">
								{{item.specName}}
							</view>
							<u-icon name="trash" class="ml-10" color="#333" size="16"></u-icon>
						</view>
					</view>
					<u-line color="#F4F4F4"></u-line>
				</view>

				<view class="">
					<view class="flex items-center justify-between py-20">
						<view class="text-28 ">
							规格值：
						</view>
						<view class="text-28  flex items-center" @click="apecificationAppend(index)">
							<view class="">
								添加
							</view>
							<u-icon name="plus" class="ml-10" color="#333" size="16"></u-icon>
						</view>
					</view>
					<u-line color="#F4F4F4"></u-line>
				</view>

				<view class="flex items-center flex-wrap" v-if="item.specValue.length != 0">
					<view class="box-4 px-16 py-12 flex items-center mt-16" v-for="(i,j) in item.specValue" :key="j" :style="{
						marginLeft:j % 4 == 0 ? '0' : '14rpx'
					}">
						<view class="">
							{{i}}
						</view>
						<u-icon name="minus-circle" class="ml-32" color="#FF3333" size="16"
							@click="deleteSpecificationValue(index,j)"></u-icon>
					</view>
				</view>
			</view>

			<!-- S 商品规格数组 productsSkus 所对应的Dom  -->
			<view class="bg-FFF round-12 py-24 px-20 mt-32" v-if="productsSkus.length != 0"
				v-for="(item,index) in productsSkus" :key="item.id">
				<!-- S 商品规格对应的规格值Dom -->
				<view class="flex items-center items-center">
					<view class="text-28  flex items-center" v-for="(i,j) in item.mallSkuSpecs"
						:key="i.specId">
						<view class="">
							{{i.specName}}:
						</view>
						<view class="">
							{{i.specValue}}
						</view>
					</view>
				</view>
				<!-- S 商品规格对应的规格值Dom -->

				<!-- <view class="text-28">
					<view class="flex items-center justify-between py-20">
						<view class=" ">
							消费金可使用数量：
						</view>
						<u--input class="text-right" placeholder="请输入消费金可使用数量" clearable type="number" v-model="item.xiaofeijinPrice"
							:disabled="skuAmend == 1">
						</u--input>
					</view>
					<u-line color="#F4F4F4"></u-line>
				</view> -->
				<view class="text-28">
					<view class="flex items-center justify-between py-20">
						<view class=" ">
							现价：
						</view>
						<u--input class="text-right" placeholder="请输入价格" clearable type="number" v-model="item.price"
							:disabled="skuAmend == 1">
						</u--input>
					</view>
					<u-line color="#F4F4F4"></u-line>
				</view>
				<view class="text-28">
					<view class="flex items-center justify-between py-20">
						<view class=" ">
							库存：
						</view>
						<u--input class="text-right" placeholder="请输入库存" clearable type="number" v-model="item.stock">
						</u--input>
					</view>
					<u-line color="#F4F4F4"></u-line>
				</view>
				<view class="text-28">
					<view class="flex items-center justify-between py-20">
						<view class=" ">
							图片：
						</view>
					</view>
					<u-line color="#F4F4F4"></u-line>
				</view>
				<htz-image-upload :max="1" v-model="item.skuIcon" @uploadSuccess="uploadEnd($event,item)"
					:action="action" :headers="headers" :disabled="skuAmend == 1">
				</htz-image-upload>
			</view>
			<!-- E 商品规格数组 productsSkus 所对应的Dom  -->

		</view>

		<!-- S 商品规格picker -->
		<u-picker @cancel="spuListShow=false" @confirm="selectConfirm" :show="spuListShow" :columns="products_specList"
			keyName="name"></u-picker>
		<!-- E 商品规格picker -->

		<!-- S 添加规格值modal -->
		<u-modal :show="showSpecification" title="规格值添加" :showCancelButton="true" @cancel="showSpecification = false"
			@confirm="apecificationAdd">
			<view class="slot-content">
				<u--input placeholder="请输入规格值" border="surround" v-model="temporarySpecification"></u--input>
			</view>
		</u-modal>
		<!-- S 添加规格值modal -->

		<view class="box-5 text-center text-32 text-FFF" v-if="productsSkus.length != 0" @click="confirm">
			确认
		</view>

		<view class="" style="height: 80rpx;">

		</view>
	</view>
</template>

<script>
	import { getToken } from '@/utils/auth'
	// 引入图片上传组件
	import htzImageUpload from '@/components/htz-image-upload/htz-image-upload.vue'
	export default {
		components: {
			htzImageUpload,
		},
		data() {
			return {
				products_specList: [], //商品规格数组
				spuListShow: false, //商品规格弹窗
				title: '商品规格', //标题
				/*
				productsSkus:[ //规格数组
					{
						xiaofeijinPrice:"",//原价
						price:"",//现价
						skuIcon:"",//图片
						stock:"",//库存
						mallSkuSpecs:[ //分类 + 规格 数组  一个分类对应多个规格值多个商品信息
							{
								specId:"",//商品规格id
								specName:"",//为了页面展示需要规格类型名
								specValue:"",//商品规格值
							}，
						]
					}
				],
				*/
				productsSkus: [],
				/*
					commercialSpecification:[
						{
							specId: value[0].id,//商品规格id
							specName: value[0].specName,//商品规格名字
							specValue: [],//商品规格下所以的规格值
						}
					]
				*/
				commercialSpecification: [

				], //商品规格数组 临时数组用来展示商品规格
				showSpecification: false, //规格值弹窗
				temporarySpecification: "", //临时规格值
				temporarySpecificationIndex: null, //临时规格值下标
				headers: {
					'Authorization': 'Bearer ' + getToken()
				},
				action: getApp().globalData.config.baseUrl + '/common/upload',
				skuAmend: 2, //如果是修改则是1
				shopId: null
			}
		},
		onLoad(e) {
			let that = this
			if (e.id) {
				this.skuAmend = 1
				this.shopId = e.id
				uni.getStorage({
					key: 'temSku',
					success: function(res) {
						that.productsSkus = res.data
						console.log('that.productsSkus',that.productsSkus)
						uni.removeStorage({
							key: 'temSku',
							success: function(res) {
								console.log('success');
							}
						});
					}
				});
			}
			this.getData()
		},
		methods: {
			// 选择商品规格
			selectSpecification() {
				// 先判断已有的商品规格和所有的商品规格数量是否相等 相等则提示
				if (this.commercialSpecification.length == this.products_specList[0].length) {
					this.$modal.msg('暂无可选商品规格')
				} else {
					this.spuListShow = true
				}
			},

			// 规格值弹窗确认
			apecificationAppend(index) {
				this.temporarySpecificationIndex = index
				this.showSpecification = true
			},

			// 规格值确认
			apecificationAdd() {
				// 给商品规格数组 规格类型添加规格值
				this.commercialSpecification[this.temporarySpecificationIndex].specValue.push(this.temporarySpecification)
				// 添加完需给临时规格值赋空 临时规格下标不用，因为临时下标是在规格值弹窗确认随着更改
				this.temporarySpecification = ''
				this.calculateProductsSkus()
			},

			// 删除规格值类型
			deleteSpecification(index) {
				this.commercialSpecification.splice(index, 1)
				this.calculateProductsSkus()
			},

			// 删除规格值 index 为规格类型的下标 j为规格值的下标
			deleteSpecificationValue(index, j) {
				this.commercialSpecification[index].specValue.splice(j, 1)
				this.calculateProductsSkus()
			},

			// 计算productsSkus
			calculateProductsSkus() {
				// 判断this.commercialSpecification是否为空,为空则productsSkus空
				if (this.commercialSpecification.length == 0) {
					this.productsSkus = []
					this.showSpecification = false
					return
				}
				// 循环商品规格数组
				for (let i = 0; i < this.commercialSpecification.length; i++) {
					// 循环内部规格值数组 如果规格值数组为空则productsSkus空
					if (this.commercialSpecification[i].specValue.length == 0) {
						this.productsSkus = []
						this.showSpecification = false
						return
					}
				}

				// 每次push前需置空
				this.productsSkus = []

				// 如果有值则开始计算productsSkus的值
				// 判断商品规格数组长度 如果等于1 则只需走一层循环
				if (this.commercialSpecification.length == 1) {
					this.commercialSpecification[0].specValue.forEach((i, j) => {
						this.productsSkus.push({
							id: j + 1,
							// xiaofeijinPrice: "", //原价
							price: "", //现价
							skuIcon: [], //图片
							stock: "", //库存
							mallSkuSpecs: [ //分类 + 规格 数组  一个分类对应多个规格值多个商品信息
								{
									specId: this.commercialSpecification[0].specId, //商品规格id
									specName: this.commercialSpecification[0].specName, //为了页面展示需要规格类型名
									specValue: i, //商品规格值
								}
							]
						})
					})
				}

				// 判断商品规格数组长度 如果等于2 则只需走俩层循环
				if (this.commercialSpecification.length == 2) {
					this.commercialSpecification[0].specValue.forEach((i, j) => {
						this.commercialSpecification[1].specValue.forEach((item, index) => {
							this.productsSkus.push({
								id: j = 1,
								// xiaofeijinPrice: "", //原价
								price: "", //现价
								skuIcon: [], //图片
								stock: "", //库存
								mallSkuSpecs: [ //分类 + 规格 数组  一个分类对应多个规格值多个商品信息
									{
										specId: this.commercialSpecification[0]
										.specId, //商品规格id
										specName: this.commercialSpecification[0]
										.specName, //为了页面展示需要规格类型名
										specValue: i, //商品规格值
									},
									{
										specId: this.commercialSpecification[1]
										.specId, //商品规格id
										specName: this.commercialSpecification[1]
										.specName, //为了页面展示需要规格类型名
										specValue: item, //商品规格值
									}
								]
							})
						})
					})
				}

				this.showSpecification = false
			},


			// 获取页面所需数据
			async getData() {
				const res = await this.$Api.store.getSpecGroupByType()
				this.products_specList.push(res.data)
				console.log(res.data, '商品属性')
			},

			/* 所属分类选择确认按钮 */
			selectConfirm(e) {
				const {
					value
				} = e
				console.log(value, 'value')

				// 判断是否选择相同商品规格
				if (this.commercialSpecification.length != 0) {
					for (let i = 0; i < this.commercialSpecification.length; i++) {
						if (this.commercialSpecification[i].specId == value[0].id) {
							this.$toast('不可选相同商品规格')
							return
						}
					}
				}
				
				// 给商品规格数组添加初始化数据
				this.commercialSpecification.push({
					specId: value[0].id,
					specName: value[0].name,
					specValue: [],
				})

				this.spuListShow = false
			},

			confirm() {
				if (this.skuAmend == 1) {
					try {
						this.productsSkus.forEach((item, index) => {
							this.$Api.store.amendSpecification({
								id: item.id,
								stock: item.stock
							}).then(res => {
								if (index == this.productsSkus.length - 1) {
									this.$modal.msg('修改成功')
									let pages = getCurrentPages();
									let prevPage = pages[pages.length - 2]; //上一个页面
									prevPage.$vm.getData(this.shopId);
									this.$tab.back(1500)
								}
							}).catch(err=>{
								throw new Error(err);
							})
						})
					} catch (e) {
						this.$modal.msg(e.message)
					}
				} else {
					// try catch 判断异常 抛出异常提示
					try {
						this.productsSkus.forEach(item => {
							if (!item.price) {
								throw new Error("价格未填写！");
							}
							if (!item.stock) {
								throw new Error("库存没有加！");
							}
							if (item.skuIcon.length == 0) {
								throw new Error("图片未上传！");
							}
						})


						let pages = getCurrentPages();
						let prevPage = pages[pages.length - 2]; //上一个页面

						prevPage.$vm.setmallSkus(this.productsSkus);
						this.$tab.back()

					} catch (e) {
						this.$modal.msg(e.message)
					}
				}
			},

			// 上传图片
			uploadEnd(res, item) {
				var _res = JSON.parse(res.data);
				if (_res.code == 200) {
					item.skuIcon.push(_res.url);
				}
				if (_res.code === 401) {
					uni.showModal({
						title: "提示",
						content: "登录状态已过期，需要重新登录！",
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								uni.reLaunch({
									url: '/pages/login'
								})
							}
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.box-1 {
		width: 100rpx;
		height: 48rpx;
	}

	.box-2 {
		border: 1rpx solid #EF0624;
	}

	.box-3 {
		background-color: #FCF5F5;
	}

	.box-4 {
		background-color: #EAEAEA;
	}

	.box-5 {
		width: 320rpx;
		height: 80rpx;
		background: #FD212C;
		line-height: 80rpx;
		margin: 150rpx auto;
	}
</style>
